package com.example.koizzi.ad20180426_weather;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final int GET_WEATHER_SUCCESS = 1001;
    private TextView tvREs;
    private Handler handler;
    private ImageView ivWeather_a,ivWeather_b,ivWeather_c,ivWeather_d,ivWeather_e;
    private TextView tv_a,tv_b,tv_c,tv_d,tv_e;
    private Weather weatherData;
    private TempView temp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        QuerryWeather("广州");
        initHandler();
    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == GET_WEATHER_SUCCESS){
                    String weatherJson = (String) message.obj;
                    weatherData = new Gson().fromJson(weatherJson, Weather.class);
                    if (weatherData.getStatus()==200){
                        initIMG(weatherData);
                    }else {
                        Toast.makeText(MainActivity.this, "请每隔3s刷新一次", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });
    }


    private void initIMG(Weather weatherData) {

        List<Weather.DataBean.ForecastBean> forecast = this.weatherData.getData().getForecast();

        String city = this.weatherData.getCity();
        String notice = this.weatherData.getData().getForecast().get(0).getNotice();
        tvREs.setText("今日 "+city+"："+notice+"!");

        String [] dates=new String [5];
        String [] type=new String [5];
        String [] fx=new String [5];
        int [] aqis=new int [5];

        for (int i=0;i<dates.length;i++){
            dates[i] = forecast.get(i).getDate();
            type[i] = forecast.get(i).getType();
            fx[i] = forecast.get(i).getFx();
            aqis[i] = forecast.get(i).getAqi();
        }

        ivWeather_a.setImageResource(getWeatherImage(type[0]));
        ivWeather_b.setImageResource(getWeatherImage(type[1]));
        ivWeather_c.setImageResource(getWeatherImage(type[2]));
        ivWeather_d.setImageResource(getWeatherImage(type[3]));
        ivWeather_e.setImageResource(getWeatherImage(type[4]));

        tv_a.setText(dates[0] + " \n" + fx[0]+"\n"+type[0]+"\n"+aqi(aqis[0]));
        tv_b.setText(dates[1] + " \n" + fx[1]+"\n"+type[1]+"\n"+aqi(aqis[1]));
        tv_c.setText(dates[2] + " \n" + fx[2]+"\n"+type[2]+"\n"+aqi(aqis[2]));
        tv_d.setText(dates[3] + " \n" + fx[3]+"\n"+type[3]+"\n"+aqi(aqis[3]));
        tv_e.setText(dates[4] + " \n" + fx[4]+"\n"+type[4]+"\n"+aqi(aqis[4]));

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）

        temp = findViewById(R.id.tempView);
        temp.setData(forecast,width,height);
    }

    private String aqi(int aqi) {
        if (aqi<=50){
            return "优";
        }else if(aqi<=100){
            return "良";
        }else if(aqi<=200){
            return "轻度污染";
        }else if(aqi<=300){
            return "中度污染";
        }else {
            return "严重污染";
        }
    }

    private void initView() {
        tvREs = findViewById(R.id.tv_Res);
        ivWeather_a = findViewById(R.id.iv_a);
        ivWeather_b = findViewById(R.id.iv_b);
        ivWeather_c = findViewById(R.id.iv_c);
        ivWeather_d = findViewById(R.id.iv_d);
        ivWeather_e = findViewById(R.id.iv_e);

        tv_a = findViewById(R.id.tv_a);
        tv_b = findViewById(R.id.tv_b);
        tv_c = findViewById(R.id.tv_c);
        tv_d = findViewById(R.id.tv_d);
        tv_e = findViewById(R.id.tv_e);
    }

    private int getWeatherImage(String type) {
        if(type.equals("晴")){
            return R.drawable.sun;
        }else if(type.equals("阵雨")){
            return R.drawable.zhenyu;
        }else if(type.equals("小雨")){
            return R.drawable.rain;
        }else if(type.equals("中雨")){
            return R.drawable.rain;
        }else if(type.equals("雷阵雨")){
            return R.drawable.thunder;
        }else if(type.equals("晴")){
            return R.drawable.sun;
        }else if(type.equals("多云")){
            return R.drawable.cloud;
        }
        return R.drawable.sun;
    }

    public void btnClick(View view) {
        int btnId = view.getId();
        switch (btnId) {
            case R.id.btn_GD:
                QuerryWeather("广州");
                break;
            case R.id.btn_BJ:
                QuerryWeather("北京");
                break;
            case R.id.btn_SH:
                QuerryWeather("上海");
                break;
            case R.id.btn_SZ:
                QuerryWeather("深圳");
                break;
            default:
                QuerryWeather("广州");
                break;

        }
    }

    private void QuerryWeather(String adr) {
        String weather = "https://www.sojson.com/open/api/weather/json.shtml?city="+adr;
        OkHttpClient okClient = new OkHttpClient();
        Request request = new Request.Builder().url(weather).build();
        Call call = okClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请等待3s后刷新
                Message msg = Message.obtain();
                msg.obj = response.body().string();
                msg.what = GET_WEATHER_SUCCESS;
                Log.e("nnn","*"+msg.obj);
                handler.sendMessage(msg);
            }
        });
    }
}
